'use strict';

var app = angular.module("myApp", ['ui.bootstrap', 'ui.bootstrap.treeview2', 'ui.select2']);
// const app = angular.module("myApp",['ui.bootstrap']);

var treeViewTemplate = '\n<tree-view ng-if="graphTree != null && graphTree.g != null" tree-service="graphTree" node-label="text"></tree-view>\n';

app.controller("manageController", ['$scope', '$compile', '$filter', '$uibModal', function ($scope, $compile, $filter, $uibModal) {
    $scope.query = {
        fault: FaultNode.faults[0]
    };

    $scope.faultModules = [];
    $scope.freeNodes = [];

    $scope.component_ref = null;

    $scope.toJSON = function (val) {
        return angular.toJson(val, true);
    };

    // $scope.faults=FaultNode.faults;
    FaultNode.loadFaults.callbacks.push(function () {
        $scope.faults = FaultNode.faults;
        $scope.$apply();
    });
    FaultNode.loadFaults.callbacks.push(function () {
        $scope.query.fault = FaultNode.faults[0];
        $scope.$apply();
    });
    FaultNode.loadFaults();

    $scope.components = ComponentNode.components;
    ComponentNode.loadComponents.callbacks.push(function () {
        return $scope.components = ComponentNode.components;
    });
    ComponentNode.loadComponents();

    // $scope.graphTree = new TreeView();
    $scope.graphTree = new NodeTreeView();
    $scope.$watch('query', function () {
        console.info($scope.query);
        if ($scope.query.fault) Graph.loadGraph($scope.query.fault.id, function (g) {
            $scope.$apply(function () {
                // angular.element("#nodeDetail2").html("");
                angular.element("#treeDiv").html("");
                delete $scope.graph;
                delete $scope.graphTree;
                $scope.graph = g;
                // g.markFreedomNode();
                $scope.freeNodes = g.getRoot().$freelist;

                $scope.graphTree = new NodeTreeView();
                $scope.graphTree.g = g;
                $scope.graphTree.collapseAll();
                console.info($scope.graphTree);

                var tp = $compile(treeViewTemplate)($scope);
                angular.element("#treeDiv").html("").append(tp);
            });
        });
    }, true);

    // $scope.$watch('graphTree.selectedNode',function () {
    //     let node = $scope.graphTree.selectedNode;
    // if($scope.graph && !!node){
    //     let template = node.getTemplate($scope.graphTree.fromEdge,$scope.graph);
    //     let tp = $compile( template )( $scope );
    //     angular.element("#nodeDetail2").html("").append( tp );
    // }
    // },true);

    $scope.filterOfFault = function (fault) {
        if ($scope.query.faultType && $scope.query.faultType != '') {
            if (fault.faultCategory != $scope.query.faultType) {
                return false;
            }
        }
        if ($scope.query.faultModule && $scope.query.faultModule != '') {
            if (fault.faultModule != $scope.query.faultModule) {
                return false;
            }
        }
        return true;
    };

    $scope.refreshModules = function () {
        getCache("fault_module", function (val) {
            $scope.faultModules = val.map(function (x) {
                if (x.indexOf(':') < 0) {
                    return {
                        category: '',
                        name: x
                    };
                }
                var arr = x.split(':', 2);
                return {
                    category: arr[0],
                    name: arr[1]
                };
            });
            $scope.faultModules.splice(0, 0, '');
        }, function (callback, cache, name) {
            getConfigure('module', function (data) {
                cache[name] = {
                    lastTimestamp: new Date().getTime(),
                    value: data
                };
                callback(data);
            });
        }, 5000);
    };
    $scope.refreshModules();

    $scope.featureChoice = [];
    $scope.reasonChoice = [];
    $scope.featFaultResult = 0;
    $scope.featResult = [];
    $scope.featResult2 = [];
    $scope.initSamples = function () {
        //初始化数据集
        $.get('http://127.0.0.1:8080/init/' + $scope.query.fault.id, function (data) {
            console.info("模型初始化为：", data);
        });
    };

    $scope.featFeature = function () {
        var feat = 0;
        for (var i = 0; i < $scope.featureChoice.length; i++) {
            feat += ($scope.featureChoice[i] || 0) * (1 << i);
        }
        $.get('http://127.0.0.1:8080/feat/' + $scope.query.fault.id + '?feature=' + feat, function (data) {
            console.info("模型匹配结果为：", data);
            $scope.featResult = data;
            $scope.$apply();
        });
    };

    $scope.trainFeature = function () {
        var feat = 0;
        var traint = 0;
        for (var i = 0; i < $scope.featureChoice.length; i++) {
            feat += ($scope.featureChoice[i] || 0) * (1 << i);
        }
        for (var _i = 0; _i < $scope.reasonChoice.length; _i++) {
            traint += ($scope.reasonChoice[_i] || 0) * (1 << _i);
        }
        $.get('http://127.0.0.1:8080/train/' + $scope.query.fault.id + '?feature=' + feat + '&reason=' + traint, function (data) {
            console.info("模型更新为：", data);
            $.get('http://127.0.0.1:8080/feat/' + $scope.query.fault.id + '?feature=' + feat, function (data) {
                console.info("新模型匹配结果为：", data);
                $scope.featResult2 = data;
                $scope.$apply();
            });
        });
    };

    $scope.persistGraph = function () {
        $scope.graph.persist(function (r) {
            return alert("数据库同步成功！");
        }, function (e) {
            return console.error(e);
        });
    };

    $scope.sortByOutId = function (f) {
        if (!f.outId) {
            return 0;
        }
        return parseInt(f.outId, 10);
    };

    // $scope.sortByEdgeId = function (edge) {
    //     return edge.id;
    // };

    $scope.nextFaults = function () {
        var currentFaults = $filter('filter')($scope.faults, { faultCategory: $scope.query.faultType });
        var currentOrdered = $filter('orderBy')(currentFaults, $scope.sortByOutId);
        var index = currentOrdered.indexOf($scope.query.fault);
        if (index < currentOrdered.length - 1) $scope.query.fault = currentOrdered[index + 1];
    };

    $scope.exportFaultAsJson = function () {
        var modalInstance = $uibModal.open({
            template: '<div>' + angular.toJson($scope.graph.toJson()) + '</div>',
            animation: true,
            size: 'lg'
        });
        // 更新页面内容
        // modalInstance.result.then(function(response) {
        // refreshByCloseStatus(response, $scope.vehicles);
        // });
    };
}]);
